package com.catazy.mvvmlib.net.http.error

import android.net.ParseException
import com.blankj.utilcode.util.LogUtils
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException

/**
 * 作者: Tao
 * 日期: 2024/1/29
 * 时间: 9:50
 * 描述: 统一错误处理工具类
 */
object ExceptionHandler {

    /**
     * 统一处理异常为ApiException
     * @param e Throwable
     * @return ApiException
     */
    fun handleException(e: Throwable): ApiException {
        LogUtils.i("handleException -> ${e.message}")
        val ex: ApiException
        when (e) {
            is ApiException -> ex = ApiException(e.errCode, e.message, throwable = e)
            is HttpException -> {
                ex = when (e.code()) {
                    Error.UNAUTHORIZED.code -> ApiException(Error.UNAUTHORIZED, e)
                    Error.FORBIDDEN.code -> ApiException(Error.FORBIDDEN, e)
                    Error.NOT_FOUND.code -> ApiException(Error.NOT_FOUND, e)
                    Error.REQUEST_TIMEOUT.code -> ApiException(Error.REQUEST_TIMEOUT, e)
                    Error.GATEWAY_TIMEOUT.code -> ApiException(Error.GATEWAY_TIMEOUT, e)
                    Error.INTERNAL_SERVER_ERROR.code -> ApiException(Error.INTERNAL_SERVER_ERROR, e)
                    Error.BAD_GATEWAY.code -> ApiException(Error.BAD_GATEWAY, e)
                    Error.SERVICE_UNAVAILABLE.code -> ApiException(Error.SERVICE_UNAVAILABLE, e)
                    else -> ApiException(e.code(), e.message(), throwable = e)
                }
            }

            is JsonParseException -> ex = ApiException(Error.PARSE_ERROR, e)
            is JSONException -> ex = ApiException(Error.PARSE_ERROR, e)
            is ParseException -> ex = ApiException(Error.PARSE_ERROR, e)
            is MalformedJsonException -> ex = ApiException(Error.PARSE_ERROR, e)
            is ConnectException -> ex = ApiException(Error.NETWORD_ERROR, e)
            is SSLException -> ex = ApiException(Error.SSL_ERROR, e)
            is SocketException -> ex = ApiException(Error.TIMEOUT_ERROR, e)
            is SocketTimeoutException -> ex = ApiException(Error.TIMEOUT_ERROR, e)
            is UnknownHostException -> ex = ApiException(Error.UNKNOW_HOST, e)
            else -> ex = if (!e.message.isNullOrEmpty()) ApiException(
                1000,
                e.message!!,
                throwable = e
            ) else ApiException(Error.UNKNOWN, e)
        }

        return ex
    }
}